const IoRedis = require('ioredis');
const log = require('../utils/log');
const resCode = require('../config/ResCode');

class Redis{
    constructor(host,port,db_index) {
        console.log('==========Redis===========')
        // this.connectRedis();

        this.ip = host;
        this.port = port;
        this.db = db_index;

        this.connectRes();
    }

    connectRes(host,port,db_index){
        return new Promise((resolve, reject)=>{
            this.redis = new IoRedis({
                host: this.ip,
                port: this.port,
                // password: 'your_password', // 如果需要密码，请取消注释并设置密码
                db: this.db,
            });
            this.isOpen = false;
            this.redis.on('ready', async () => {
                log.error('Redis链接成功');
                resolve(this.redis);
            })
            this.redis.on('error', err => {
                if (err) {
                    log.error('Redis链接错误',err);
                }
            })
        })
    }

    async quit() {
        try {
            this.redis.quit();
            this.redis = null;
            log.error('Redis链接关闭');
        } catch (err) {
            log.warn('Error disconnecting Redis client:', err);
        }
    }

    async set(key, value) {
        console.log('======this.isOpen===========',this.isOpen)
        try {
            await this.connectRes();
            await rds.set(key, value);
            console.log(`Set key "${key}" to "${value}"`);
        } catch (err) {
            console.log('Error setting key:', err);
        }finally {
            // await this.quit();
        }
    }

    async get(key) {
        try {
            await this.connectRes();
            const value = await this.redis.get(key);
            console.log(`Value of key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error getting key:', err);
        }finally {
            // await this.quit();
        }
    }

    //删除键
    async del(key,callback){
        try {
            await this.connectRes();
            const value = await this.redis.del(key);
            console.log(`Value of del key "${key}": ${value}`);
            return value;
        }catch (e) {
            console.log('Error del key:', err);
        }finally {
            // await this.quit();
        }
    }

    async hmset(key, field, data){
        log.info("======hmset=========",key);
        try {
            await this.connectRes();
            const value = await this.redis.hset(key, field, data);
            console.log(`Value of key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error getting key:', err);
        }finally {
            // await this.quit();
        }
    }
    async hmget(key, obj, callback){
        try {
            await this.connectRes();
            const value = await this.redis.hmset(key,obj);
            console.log(`Value of hmget key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error hmget key:', err);
        }finally {
            // await this.quit();
        }
    }

    async hgetall(key){
        try {
            await this.connectRes();
            const value = await this.redis.hgetall(key);
            console.log(`Value of hgetall key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error hgetall key:', err);
        }finally {
            // await this.quit();
        }
    }

    async hset(key, field, newValue){
        try {
            await this.connectRes();
            const value = await this.redis.hset(key,field,newValue);
            console.log(`Value of hset key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error hset key:', err);
        }finally {
            // await this.quit();
        }
    }

    //往列表里面添加
    async lpush(key,data){
        log.info('=========lpush==============',key);
        try {
            await this.connectRes();
            const value = await this.redis.lpush(key,JSON.stringify(data));
            console.log(`Value of lpush key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error lpush key:', err);
        }finally {
            // await this.quit();
        }
    }

    //按条件查找
   async lrange(key,start, end){
        try {
            // log.info('====lrange1==============');
            if (!this.redis) {
                await this.connectRes();
            }
            // log.info('====lrange==============');
            let value = await this.redis.lrange(key, start, end);
            console.log(`Value of key "${key}": ${value}`);
            return value;
        }catch (err) {
            console.log('Error lrange key:', err);
        }finally {
            // await this.quit();
        }
    }

    //列表修改
    async lset(key, index, data) {
        try {
            await this.connectRes();
            const value = await this.redis.lset(key, index, data);
            console.log(`Value of lset key "${key}": ${value}`);
            return value;

        } catch (err) {
            console.log('Error lset key:', err);
        } finally{
            // await this.quit();
        }
    }

    //列表删除
    async lrem(key,index,data){
        try {
            await this.connectRes();
            const value = await this.redis.lrem(key, index, data);
            console.log(`Value of lrem key "${key}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error lrem key:', err);
        }finally {
            // await this.quit();
        }
    }

    //清空列表
    async ltrim(listKey) {
        try {
            await this.connectRes();
            const value = await this.redis.ltrim(listKey, 1, 0);
            console.log(`Value of ltrim key "${listKey}": ${value}`);
            return value;
        } catch (err) {
            console.log('Error ltrim key:', err);
        }finally {
            // await this.quit();
        }

    }
}

module.exports = Redis;